package Ali;

/**
 * 给你一个正整数 n ，生成一个包含 1 到 n2 所有元素，且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix 。
 * @author le
 */
public class Test16
{
    public static void main(String[] args)
    {
        int[][] p = generateMatrix(3);
        for (int i = 0;i < p.length;i++){
            for (int j = 0;j < p[0].length;j++){
                System.out.print(p[i][j]);
            }
        }
    }

    public static int[][] generateMatrix(int n) {
        int top = 0;
        int left = 0;
        int bottom = n-1;
        int right = n-1;
        int index = 1;
        int[][] res = new int[n][n];
        while (top <= bottom && left <= right){
             for (int i = left;i <= right;i++){
                 res[top][i] = index;
                 index++;
             }

             for (int i = top +1;i <= bottom;i++){
                 res[i][right] = index;
                 index++;
             }

             for (int i = right-1;i >= left;i--){
                 res[bottom][i] = index++;
             }

             for (int i = bottom-1;i > top;i--){
                 res[i][left] = index++;
             }


            top++;
            left++;
            bottom--;
            right--;

        }
        return res;


    }
}
